// eslint-disable-next-line no-undef, @typescript-eslint/no-var-requires
const fs = require('fs');

const packageTxt = fs.readFileSync('package.json', 'utf8');
const packageJson = JSON.parse(packageTxt);

const customContributesTxt = fs.readFileSync('data/contributes.json', 'utf8');
const custonContributes = JSON.parse(customContributesTxt);

const { active, common } = custonContributes;
const activeContributes = custonContributes[active];

const contributes = common;

// 处理 configuration
const configuration = activeContributes.configuration;
if (configuration && configuration[0]) {
  const { properties } = configuration[0];
  if (properties) {
    Object.keys(properties).forEach(key => {
      contributes.configuration[0].properties[key] = properties[key];
    });
  }
}

// 处理 commands
const commands = activeContributes.commands;
if (Array.isArray(commands)) {
  contributes.commands = contributes.commands.concat(commands);
}
// 处理 "menus"
const menus = activeContributes.menus;
if (menus) {
  Object.keys(menus).forEach(key => {
    const menuObj = menus[key];
    if (Array.isArray(menuObj)) {
      if (contributes.menus[key]) {
        contributes.menus[key] = contributes.menus[key].concat(menus[key]);
      } else {
        contributes.menus[key] = menus[key];
      }
    }
  });
}
// 处理 "viewsWelcome"
const viewsWelcome = activeContributes.viewsWelcome;
if (Array.isArray(viewsWelcome)) {
  contributes.viewsWelcome = contributes.viewsWelcome.concat(viewsWelcome);
}
// 处理 "viewsContainers"
const viewsContainers = activeContributes.viewsContainers;
if (viewsContainers) {
  Object.keys(viewsContainers).forEach(key => {
    const container = viewsContainers[key];
    if (contributes.viewsContainers[key]) {
      contributes.viewsContainers[key] = contributes.viewsContainers[key].concat(container);
    } else {
      contributes.viewsContainers[key] = container;
    }
  });
}
// 处理 "views"
const views = activeContributes.views;
if (views) {
  Object.keys(views).forEach(key => {
    contributes.views[key] = views[key];
  });
}
// 处理 "customEditors"
const customEditors = activeContributes.customEditors;
if (customEditors) {
  contributes.customEditors = contributes.customEditors.concat(customEditors);
}

packageJson.contributes = contributes;

fs.writeFileSync('package.json', JSON.stringify(packageJson, null, 2), 'utf8');

// eslint-disable-next-line no-undef
console.log('update package.json done');
